package com.listeningframework.boot.autoconfigure.webmvc.validate;

import com.listeningframework.boot.commons.math.DecimalUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * @author lixining
 * @version $Id: ListeningDecimalSizeValidator.java, v 0.1 2016年5月5日 下午4:19:01 lixining Exp $
 * Decimal Size Validator
 */
public class ListeningDecimalSizeValidator implements ConstraintValidator<ListeningDecimalSize, BigDecimal> {
    /**
     * Error Message
     */
    private String message;
    /**
     * 最小值
     */
    private String min;
    /**
     * 最大值
     */
    private String max;

    /**
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(ListeningDecimalSize constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
        this.message = constraintAnnotation.message();
    }

    /**
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
        if (value != null) {
            BigDecimal minDecimal = DecimalUtils.getDeciaml(min);
            BigDecimal maxDecimal = DecimalUtils.getDeciaml(max);
            if (DecimalUtils.gte(value, minDecimal) || DecimalUtils.gte(maxDecimal, value)) {
                return true;
            }
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }

}
